<script type="text/javascript">
  var TableManaged = function () {
    return {
      //main function to initiate the module
      init: function () {
        $('#bigkey_tableDataList').dataTable({
          "lengthChange": false,
          "pageLength": 15,
          "language": {
            "lengthMenu": "Display _MENU_ records",
            "paginate": {
              "previous": "<",
              "next": ">"
            },
            "info": "共_PAGES_页,_TOTAL_条"
          }
        });

        $('#bigkey_tableDataList_wrapper>div:first-child').css("display", "none");
      }
    };
  }();

  $(function () {
    $('.selectpicker').selectpicker({
      'selectedText': 'cat',
      'size': 8,
      'dropupAuto': false
    });
    TableManaged.init();
  });

  $('#modal-memoryUsedResult').on('shown.bs.modal', function (e) {
    $('#modal-memoryUsedtitle').html('');
    $('#memoryUsedResultCount').html('');
    $('#memoryUsedResultTable').html('');

    var redisKey = $(e.relatedTarget).data('rediskey');
    console.log("rediskey:" + redisKey);
    var title = $(e.relatedTarget).data('title');
    $('#modal-memoryUsedtitle').html(title);
    $.get(
            '${request.contextPath}/manage/app/tool/diagnostic/data.json',
            {
              redisKey: redisKey,
              type: 1
            },
            function (data) {
              $('#memoryUsedResultCount').append(
                      '<tr>' +
                      '<td>key (共计' + data.count + '个）</td>' +
                      '<td>memoryUsed</td>' +
                      '</tr>'
              );
              var memoryUsedResultMap = data.result;
              for (var key in memoryUsedResultMap) {
                $('#memoryUsedResultTable').append(
                        '<tr>' +
                        '<td>' + key + '</td>' +
                        '<td>' + (memoryUsedResultMap[key] / 1024).toFixed(2) + 'K (' + memoryUsedResultMap[key] + 'bytes)</td>' +
                        '</tr>'
                );
              }
            }
    );

  });

  function changeAppIdSelect(appId, instance_select) {
    console.log('instance_select:' + instance_select);
    console.log(appId);

    document.getElementById(instance_select).options.length = 0;
    $('#' + instance_select).selectpicker('destroy');
    $('#' + instance_select).selectpicker();

    $.post('${request.contextPath}/manage/app/tool/diagnostic/appInstances',
            {
              appId: appId,
            },
            function (data) {
              var status = data.status;
              if (status == 1) {
                $('#' + instance_select).selectpicker('destroy');
                var appInstanceList = data.appInstanceList;
                $('#' + instance_select).append("<option value=''>所有主节点</option>");
                for (var i = 0; i < appInstanceList.length; i++) {
                  var val = appInstanceList[i].hostPort;
                  var term = appInstanceList[i].hostPort + '（角色：' + appInstanceList[i].roleDesc + '）'
                  $('#' + instance_select).append("<option value='" + val + "'>" + term + "</option>");
                }
                $('#' + instance_select).selectpicker();
              } else {
                console.log('data.status:' + status);
              }
            }
    );
  }

  function submitDiagnostic(type) {

    var appId;
    var size;
    var bytesFrom;
    var nodes;
    var params = [];
    if (type == 1) {
      appId = $('#bigkey-select').selectpicker('val');

      if (appId == null || appId == '') {
        alert("请选择应用");
        return;
      }
      nodes = $('#bigkey_instance-select').selectpicker('val');
      size = $('#bigkey_size-select').val();
      bytesFrom = $('#bigkey-from-select').val();
      params.push(bytesFrom);
      params.push(size);
    }

    $.post(
            '${request.contextPath}/manage/app/tool/diagnostic/submit.json',
            {
              type: type,
              appId: appId,
              nodes: nodes == null ? "" : nodes.toString(),
              params: params.toString()
            },
            function (data) {
              var status = data.status;
              if (status == 'success') {
                alert("检测任务提交成功，任务id：" + data.taskId);
                location.href = "${request.contextPath}/manage/app/tool/index?tabTag=memoryUsed";
              } else {
                toastr.error("检测任务提交失败,请查看系统日志确认相关原因!");
              }
            }
    );
  }

  function testisNum(id) {
    var value = document.getElementById(id).value;
    if (value != "" && isNaN(value)) {
      alert("字节数请填入整数");
      document.getElementById(id).value = "";
      document.getElementById(id).focus();
      return false;
    }
    return true;
  }
</script>

<div class="card">
  <div class="card-body">
    <form class="row align-items-center" role="form" name="ec">
      <div class="col-md-3">
        <select id="bigkey-select" name="appId" class="selectpicker show-tick w-100 border rounded"
                data-live-search="true" title="选择应用"
                onchange="changeAppIdSelect(this.value,'bigkey_instance-select')">
          <option value="">选择应用</option>
          <#list appDescMap?keys as key>
            <#assign appDesc = appDescMap?api.get(key)>
            <option value="${appDesc.appId!}" title="${appDesc.appId!} ${appDesc.name!}">
              【${appDesc.appId!}】&nbsp;名称：${appDesc.name!}&nbsp;类型：${appDesc.typeDesc!}&nbsp;版本：${appDesc.versionName!}
            </option>
          </#list>
        </select>
      </div>
      <div class="col-md-3">
        <select id="bigkey_instance-select" name="nodes"
                class="selectpicker show-tick w-100 border rounded" multiple
                data-live-search="true" title="选择实例">
        </select>
      </div>
      <div class="col-auto">
        <select id="bigkey_size-select" name="size" class="form-select w-100" title="数量">
          <option value="20">
            top 20
          </option>
          <option value="50">
            top 50
          </option>
          <option value="100">
            top 100
          </option>
          <option value="200">
            top 200
          </option>
          <option value="500">
            top 500
          </option>
        </select>
      </div>
      <div class="col-auto">
        <select id="bigkey-from-select" name="size" class="form-select w-100" title="数量">
          <option value="10">
            > 10K
          </option>
          <option value="50">
            > 50K
          </option>
          <option value="200">
            > 200K
          </option>
          <option value="500">
            > 500K
          </option>
          <option value="1024">
            > 1M
          </option>
        </select>
      </div>
      <div class="col-auto">
        <button type="button" class="btn btn-success" onclick="submitDiagnostic(1)">提交检测</button>
      </div>
    </form>
  </div>

  <div class="card-header">
    <h3 class="card-title">memoryUsed诊断任务列表</h3>
  </div>

  <div class="card-body">
    <form class="row" role="form" method="post" action="${request.contextPath}/manage/app/tool/index?tabTag=memoryUsed" id="appList" name="ec">
      <div class="col-md-2">
        <input type="text" class="form-control" id="appId" name="appId"
               value="${appId!}" placeholder="应用id">
      </div>
      <div class="col-md-2">
        <input type="text" class="form-control" id="parentTaskId" name="parentTaskId"
               value="${parentTaskId!}" placeholder="任务id">
      </div>
      <div class="col-md-2">
        <input type="text" class="form-control" id="auditId" name="auditId"
               value="${auditId!}" placeholder="审批id">
      </div>

      <div class="col-auto">
        <select name="diagnosticStatus" class="form-select">
          <option value="" <#if !(diagnosticStatus??) || (diagnosticStatus?? && (diagnosticStatus == ''))>selected</#if>>
          诊断状态
          </option>
          <option value="0" <#if diagnosticStatus?? && (diagnosticStatus == 0)>selected</#if>>
          诊断中
          </option>
          <option value="1" <#if diagnosticStatus?? && (diagnosticStatus == 1)>selected</#if>>
          诊断完成
          </option>
          <option value="2" <#if diagnosticStatus?? && (diagnosticStatus == 2)>selected</#if>>
          诊断异常
          </option>
        </select>
      </div>
      <button type="submit" class="btn btn-success col-auto">查询</button>
    </form>
    <br/>
    <div class="row">
      <div class="col-md-12">
        <div class="portlet box light-grey table-responsive" id="clientIndex">
          <table class="table table-striped table-bordered table-hover table-sm" id="bigkey_tableDataList" style="white-space: nowrap">
            <thead>
            <tr>
              <td>序号</td>
              <th>appId</th>
              <th>应用名称</th>
              <th>诊断类型</th>
              <th>任务id</th>
              <th>子任务id</th>
              <th>审批id</th>
              <th>节点</th>
              <th>诊断条件</th>

              <th>创建时间</th>
              <th>诊断状态</th>
              <th>诊断耗时</th>
              <th>诊断结果</th>
            </tr>
            </thead>
            <tbody>
            <#list diagnosticTaskRecordList as record>
              <#assign app_id = record.appId>
              <tr>
                <td>${record_index + 1}</td>
                <td>
                  <a target="_blank" href="${request.contextPath}/manage/app/index?appId=${app_id!}">${app_id!}</a>
                </td>
                <td>
                  <a target="_blank"
                     href="${request.contextPath}/admin/app/index?appId=${app_id!}"><#if app_id?? && appDescMap?? && appDescMap?api.get(app_id)??>${appDescMap?api.get(app_id).name!}</#if></a>
                </td>
                <td>
                  memoryUsed诊断
                </td>
                <td>
                  <a target="_blank" href="${request.contextPath}/manage/task/flow?taskId=${record.parentTaskId!}">
                    ${record.parentTaskId!}
                  </a>
                </td>
                <td>
                  <a target="_blank" href="${request.contextPath}/manage/task/flow?taskId=${record.taskId!}">
                    ${record.taskId!}
                  </a>
                </td>
                <td>
                  <a target="_blank"
                     href="${request.contextPath}/manage/app/auditList?auditId=${record.auditId!}">
                    ${record.auditId!}
                  </a>
                </td>
                <td>
                  ${record.node!}
                </td>
                <td>
                  ${record.diagnosticCondition!}
                </td>
                <td>
                  ${record.createTime!?string("yyyy-MM-dd HH:mm:ss")}
                </td>
                <td>
                  <#if (record.status==0)>诊断中</#if>
                  <#if (record.status==1)>诊断完成</#if>
                  <#if (record.status==2)>诊断异常</#if>
                </td>
                <td>
                  <#if (record.status==1)>${record.formatCostTime!}</#if>
                </td>
                <td>
                  <#if (record.status==1) && (record.type!=4)>
                    <button type="button" class="btn btn-sm btn-info"
                            data-bs-target="#modal-memoryUsedResult" data-bs-toggle="modal"
                            data-rediskey="${record.redisKey!}"
                            data-title="应用${app_id!} 节点${record.node!}">
                      查看结果
                    </button>
                  </#if>
                </td>
              </tr>
            </#list>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<div id="modal-memoryUsedResult" class="modal fade" tabindex="-1">
  <div class="modal-dialog" style="width: 100%">
    <div class="modal-content">

      <div class="modal-header">
        <h4 class="modal-title">
          诊断结果
          <small><label id="modal-memoryUsedtitle" style="color: #00BE67"></label></small>
        </h4>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-hidden="true"></button>
      </div>

      <form class="form-horizontal form-bordered form-row-stripped">
        <div class="modal-body" style="height:500px; overflow:scroll;">
          <div class="row">
            <!-- 控件开始 -->
            <div class="col-md-12">
              <table class="table table-bordered table-striped table-hover">
                <thead id="memoryUsedResultCount"></thead>
                <tbody id="memoryUsedResultTable"></tbody>
              </table>
            </div>
          </div>
        </div>

        <div class="modal-footer">
          <button type="button" data-bs-dismiss="modal" class="btn btn-secondary">Close</button>
        </div>
      </form>
    </div>
  </div>
</div>